import { Injectable, signal } from '@angular/core';
import { Observable, tap } from 'rxjs';
import { JiuGaiXiangMu } from '../models/jiugaixiangmu.model';
import { JiuGaiXiangMuSimple } from '../models/jiugaixiangmusimple.model';
import { DUMMY_JIUGAIXAINGMU } from './jiugaixiangmu';
import { MyBaseService } from './mybaseservice.service';

@Injectable({
  providedIn: 'root'
})
export class JiuGaiXiangMuService extends MyBaseService {
  private _allJiuGaiXiangMu = signal<JiuGaiXiangMu[]>([]);
  private _allJiuGaiXiangMuSimple = signal<JiuGaiXiangMuSimple[]>([]);
  get allXiangMu() {
    return this._allJiuGaiXiangMu.asReadonly();
  }

  get allXiangMuSimple(){
    return this._allJiuGaiXiangMuSimple.asReadonly();
  }

  constructor() {
    super();
    //如果不启动后端，请加载假数据
    this._allJiuGaiXiangMu.set(DUMMY_JIUGAIXAINGMU.map((item: any) => new JiuGaiXiangMu(item)));
    this._allJiuGaiXiangMuSimple.set(DUMMY_JIUGAIXAINGMU.map((item: any) => new JiuGaiXiangMuSimple(item)));
  }

  getAllJiuGaiXiangMu(): Observable<JiuGaiXiangMu[]> {
    return this.httpClient.get<JiuGaiXiangMu[]>(this.backendURL + "/jiugaixiangmu/all").pipe(
      tap({
        next: data => this._allJiuGaiXiangMu.set(data)
      })
    );
  }

  getJiuGaiXiangMuByID(id: string): Observable<JiuGaiXiangMu> {
    return this.httpClient.get<JiuGaiXiangMu>(this.backendURL + "/jiugaixiangmu/" + id);
  }

  createJiuGaiXiangMu(data: JiuGaiXiangMu): Observable<JiuGaiXiangMu> {//后端成功添加后，本地_allJiuGaiXiangMu更新数据
    return this.httpClient.post<JiuGaiXiangMu>(this.backendURL + "/jiugaixiangmu", data).pipe(
      tap({
        next: newItem => this._allJiuGaiXiangMu.update(items => [...items, newItem])
      })
    );
  }

  updateJiuGaiXiangMu(data: JiuGaiXiangMu): Observable<JiuGaiXiangMu> {//后端成功更新数据后，本地_allJiuGaiXiangMu更新数据
    return this.httpClient.put<JiuGaiXiangMu>(this.backendURL + "/jiugaixiangmu", data).pipe(
      tap({
        next: updatedItem => this._allJiuGaiXiangMu.update((previewArray) => {
          let index = previewArray.findIndex(item => item.xiangmuid === updatedItem.xiangmuid);
          if (index !== -1) {
            previewArray[index] = updatedItem;
          }
          return previewArray;
        })
      })
    );
  }

  deleteJiuGaiXiangMu(id: number): Observable<void> {
    return this.httpClient.delete<void>(this.backendURL + "/jiugaixiangmu/" + id).pipe(
      tap({
        next: () => this._allJiuGaiXiangMu.update(items => items.filter(item => item.xiangmuid !== id))
      })
    );
  }
}
